﻿using DotNetExtensions.AspNet.HttpClients;
using DotNetExtensions.AspNet.Restful;
using Newtonsoft.Json;
using Habi.Solver.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace Habi.Solver.Services
{
    public interface IHttpRequestService
    {
        ApiResult<T> Get<T>(string url, params object[] args) where T : class;
        ApiResult<T> Post<T>(string url, object data, bool serialize = true) where T : class;

        ApiResult Get(string url, params object[] args);
        ApiResult Post(string url, object data, bool serialize = true);
    }


    public class HttpRequestService : IHttpRequestService
    {
        private readonly IHttpClient httpClient;
        public HttpRequestService()
        {
            httpClient = HttpClientFactory.Default.Create(HttpClientFactory.HttpClientKind.Restful);
        }
        public ApiResult<T> Post<T>(string url, object data, bool serialize = true) where T : class
        {
            string jsonData = serialize ? JsonConvert.SerializeObject(data) : Convert.ToString(data);
            
            return httpClient.Post(url, Encoding.UTF32.GetBytes(jsonData)).To<T>();
        }

        public ApiResult<T> Get<T>(string url, params object[] args) where T : class
        {
            if (args != null && args.Length > 0) url = string.Format(url, args);

            return httpClient.Get(url).To<T>();
        }

        public ApiResult Post(string url, object data, bool serialize = true)
        {
            string jsonData = serialize ? JsonConvert.SerializeObject(data) : Convert.ToString(data);

            return httpClient.Post(url, Encoding.UTF32.GetBytes(jsonData)).To();
        }

        public ApiResult Get(string url, params object[] args)
        {
            if (args != null && args.Length > 0) url = string.Format(url, args);

            return httpClient.Get(url).To();
        }
    }
}
